package com.filetransfer.util;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 网络相关工具类
 */
@Slf4j
public class NetworkUtil {
    
    /**
     * 获取本机IP地址
     * 优先返回局域网IP（192.168.x.x或10.x.x.x或172.x.x.x）
     */
    public static String getLocalIpAddress() {
        try {
            String localAreaNetworkIp = getLocalAreaNetworkIp();
            if (localAreaNetworkIp != null) {
                log.info("获取到局域网IP: {}", localAreaNetworkIp);
                return localAreaNetworkIp;
            }
            
            // 如果没有找到局域网IP，返回本机地址
            String localhost = InetAddress.getLocalHost().getHostAddress();
            log.info("未找到局域网IP，使用本地IP: {}", localhost);
            return localhost;
        } catch (Exception e) {
            log.error("获取本机IP地址失败", e);
            return "127.0.0.1";
        }
    }
    
    /**
     * 获取局域网IP地址
     * 192.168.x.x或10.x.x.x或172.16.x.x-172.31.x.x
     */
    private static String getLocalAreaNetworkIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                
                // 跳过禁用、环回和虚拟接口
                if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual()) {
                    continue;
                }
                
                // 优先使用有线网卡
                String interfaceName = networkInterface.getName().toLowerCase();
                boolean isWired = interfaceName.startsWith("eth") || interfaceName.startsWith("en");
                
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                
                // 存储候选IP
                String lanIp = null;
                
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    String ip = address.getHostAddress();
                    
                    // 排除IPv6和回环地址
                    if (ip.contains(":") || address.isLoopbackAddress()) {
                        continue;
                    }

                    // 检查是否是局域网IP
                    if (isPrivateIp(ip)) {
                        log.debug("在网卡{}上找到局域网IP: {}, 是否有线: {}", interfaceName, ip, isWired);
                        
                        // 如果是有线网卡，直接返回
                        if (isWired) {
                            return ip;
                        }
                        
                        // 存储为候选IP
                        lanIp = ip;
                    }
                }
                
                // 如果找到了局域网IP但不是有线网卡的，保存起来
                if (lanIp != null) {
                    return lanIp;
                }
            }
            
            return null;
        } catch (SocketException e) {
            log.error("获取网络接口失败", e);
            return null;
        }
    }
    
    /**
     * 判断是否为内网IP
     * 10.0.0.0/8
     * 172.16.0.0/12
     * 192.168.0.0/16
     */
    private static boolean isPrivateIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        
        String[] segments = ip.split("\\.");
        if (segments.length != 4) {
            return false;
        }
        
        try {
            int firstSegment = Integer.parseInt(segments[0]);
            int secondSegment = Integer.parseInt(segments[1]);
            
            // 10.x.x.x
            if (firstSegment == 10) {
                return true;
            }
            
            // 172.16.x.x - 172.31.x.x
            if (firstSegment == 172 && secondSegment >= 16 && secondSegment <= 31) {
                return true;
            }
            
            // 192.168.x.x
            return firstSegment == 192 && secondSegment == 168;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    
    /**
     * 获取客户端真实IP地址
     */
    public static String getClientIpAddress(String requestIp) {
        if (requestIp != null && !requestIp.isEmpty() && !requestIp.equalsIgnoreCase("unknown")) {
            // 如果是多级代理，获取第一个非unknown的IP
            if (requestIp.contains(",")) {
                requestIp = requestIp.split(",")[0].trim();
            }
            
            // 排除本地测试IP
            if (!requestIp.equals("127.0.0.1") && !requestIp.equals("0:0:0:0:0:0:0:1")) {
                return requestIp;
            }
        }
        
        // 如果没有获取到客户端IP，返回服务器IP
        return getLocalIpAddress();
    }
} 